const router = require("koa-router")();
const nodemailer = require("nodemailer");

/**
 * api {post} /home/sendEmail 发送邮件
 *
 * apiParam {String} mails 邮箱列表
 *
 */
router.post("/sendEmail", async (ctx, nex) => {
  const user = ctx.user;
  const { mails } = ctx.post;
  const email = await BaaS.Models.email.query({}).fetch();
  const transporter = nodemailer.createTransport({
    service: email.service,
    auth: {
      user: email.user,
      pass: email.pass // 授权码,通过QQ获取
    }
  });
  // http://dev.qingful.com/home/public/register?inviter=${user}
  const mailOptions = {
    from: email.from, // 发送者
    to: `${mails}`, // 接受者,可以同时发送多个,以逗号隔开
    subject: email.subject, // 标题
    html: `您的好友${
      user.user_info.nickname
    }，正在使用青否云，效率提升了50%，成本节省了75%！<a href=http://dev.qingful.com/home/public/register?inviter=${
      ctx.header.token
    }>快来看看吧！</a>`
  };
  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      console.log(err);
      return;
    }
    console.log("发送成功");
  });
  ctx.success("发送成功");
});
/**
 * api {get} /home/sendEmail 我邀请的好友
 *
 */
router.get("/myInviter", async (ctx, nex) => {
  const user = ctx.user;
  const myInviter = await BaaS.Models.invite_user
    .query({
      where: { user_id: user.id }
    })
    .fetchAll({ withRelated: ["user.avater"] });
  ctx.success(myInviter);
});
/**
 * api {get} /home/invitUrl 获取邀请好友的链接
 *
 */
router.get("/invitUrl", async (ctx, nex) => {
  const token = ctx.header.token;
  const invitUrl = `http://dev.qingful.com/home/public/register?inviter=${token}`;
  ctx.success(invitUrl);
});

module.exports = router;
